﻿///////////////////////////////////////////////////////////////////////////////
// File:        ServerThread.cc
// Author:      671643387@qq.com
// Description:
///////////////////////////////////////////////////////////////////////////////

#include <boost/bind.hpp>

#include "nio/net/ServerThread.hpp"
using namespace nio::net;


ServerThread::ServerThread()
    : connLoad_(0)
    , eventLoop_()
    , removeConnectionFN_()
{

}

ServerThread::~ServerThread()
{

}

void ServerThread::run()
{
    eventLoop_.run();
}

void ServerThread::stop()
{
    eventLoop_.stop();
}

void ServerThread::addConnection(ConnectionPtr& conn)
{
    incLoad();
    eventLoop_.queue(boost::bind(&ServerThread::doAddConnection, this, conn));
}

void ServerThread::doAddConnection(ConnectionPtr& conn)
{
    if (eventLoop_.getReactor()->addSource(conn->getSocket().getSOCKET(),
        Reactor::RE_ALL, conn.get()))
    {
        conn->setShutdownFN(boost::bind(&ServerThread::shutdownConnection, this, _1));
        addConnectionFN_(conn);
        return;
    }

    decLoad();
    removeConnectionFN_(conn.get());
}

void ServerThread::shutdownConnection(Connection* conn)
{
    eventLoop_.queue(boost::bind(&ServerThread::doShutdownConnection, this, conn));
}

void ServerThread::doShutdownConnection(Connection* conn)
{
    eventLoop_.getReactor()->removeSource(conn->getSocket().getSOCKET());
    decLoad();
    removeConnectionFN_(conn);
}


